<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="UTF-8">
    <link href="css/message.css" rel='stylesheet'>
    <link href="css/common.css" rel='stylesheet'>
    <title>Title</title>
    <script src="http://47.106.66.89:8080/js/vue.min.js"></script>
    <!-- ele 的引入放在vue下面-->
    <link href="http://47.106.66.89:8080/js/ele-2.15.7/theme-chalk/index.css" rel="stylesheet">
    <script src="http://47.106.66.89:8080/js/ele-2.15.7/index.js"></script>
    <script src="http://47.106.66.89:8080/js/axios.min.js"></script>
    <script src = 'plug-in/jquery-2.2.0.min.js' type='text/javascript'></script>

    <script src="/js/common.js"></script>
    <script src="/b-chat/js/ws.js"></script>
</head>
<body>


<div id="app">
    <ws ref="w" :msgs.sync="msgs" :users.sync="users" prefix="ws://127.0.0.1:8004/"></ws>
    <!-- 导航栏 -->
    <common @logined="a"></common>

    <div class="chat-container">
        <!-- 左侧导航 -->
        <ul class="left-sidebar" style="list-style: none">消息中心
            <li class="nav-item active">我的消息</li>
            <li class="nav-item">回复我的</li>
            <li class="nav-item">收到的赞</li>
            <li class="nav-item">系统通知</li>
            <li class="nav-item">消息设置</li>
        </ul>

        <!-- 中间消息列表 -->
        <div class="message-list" id="messageList">
            <div class="message-item" v-for="(user, id) in relationship" v-if="user.id != myinfo.id">
                <div class="avatar">
                    <img :src="user.headimg" @click="chooserecv(user.id, id)">
                </div>
                <div class="content">
                    <div class="header">
                        <span  class="username" @click="recvId = recvId == user.id ? user.id : user.id" :style="{color: recvId == user.id ? 'blue' : 'unset'}">{{user.name}}</span>
                        <span class="time"></span>
                    </div>
                    <div class="preview">

                    </div>
                </div>
            </div>
        </div>

                        <!-- 右侧聊天窗口 -->
        <div class="chat-window">
            <div class="chat-header">
                <div class="user-info" v-for="user in relationship" v-if="user.id == recvId">
                    <img :src="user.headimg" alt="avatar">
                    <span>{{user.name}}</span>
                </div>
            </div>
            <div class="chat-messages" id="chatMessages" ref="chatMessages">
                <div v-for="m in oldmsgs" :class="m.id == myinfo.id ? 'send':'recv'">
                    <div class="chat-header">
                        <div class="user-info" style=" display: flex;flex-direction: column;justify-content: end;align-items: center;">
                            <label class="user">{{m.name}}</label>
                            <img :src="m.headimg" alt="avatar">

                        </div>
                    </div>

                    <span class="msg" style=" position: relative; top: 55px;">

                         <img class="msg" v-if="m.content.startsWith('img:')" :src="m.content.substring(4)" style="width: 300px">
                         <span v-else :class="m.id == myinfo.id ? 'send-time':'recv-time'">{{m.content}}</span>
                         <br>
                         <span class="time">{{m.time.toString().replace('T', ' ')}}</span>

                    </span>
                    <br><br><br>
                </div>

                <p style="color: skyblue; font-size: larger; display: flex; justify-content: center; padding: 80px" v-if="recvId">以上是历史聊天</p>


                <div v-for="m in msgs" :class="m.author && m.author.id == myinfo.id ? 'send':'recv'">
                    <div class="chat-header">
                        <div class="user-info" style=" display: flex;flex-direction: column;justify-content: end;align-items: center;">
                            <label class="user">{{m.author.name}}</label>
                            <img :src="m.author.headimg" alt="avatar">

                        </div>
                    </div>

                    <span class="msg" style=" position: relative;top: 55px;">

                         <img class="msg" v-if="m.content.startsWith('img:')" :src="m.content.substring(4)" style="width: 300px">
                         <span v-else :class="m.author && m.author.id == myinfo.id ? 'send-time':'recv-time'">{{m.content}}</span>
                         <br>
                         <p class="time">{{m.time.toString().replace('T', ' ')}}</p>

                    </span>
                    <br><br><br>
                </div>
            </div>

            <div class="input-area">
                <textarea id="messageInput" placeholder="输入消息..." v-model="text" @paste="psate"></textarea>
                <button id="send" @click="sends()" >发送</button>
            </div>
        </div>
    </div>

</div>
</body>
<script>
    var v = new Vue({
        el : "#app",
        data : {
            relationship:{},
            msgs:[],
            oldmsgs:[],
            recvId: "",
            text: "",

            myinfo:{},

            // 在线用户
            users:[],

        },
        created() {
            console.log(new Date().toLocaleString())
        },
        methods : {
            a(myinfo){
                this.myinfo  = myinfo;
                this.login();
                this.relationshipById()
            },

            login(){
                this.$refs.w.login(this.myinfo.id);

            },
            sends(){
                let isSend = false;
                // 在线发送
                this.users.forEach(user=>{
                    console.log(user.id , '===', this.recvId)
                    if(user.id == this.recvId){
                        if(!this.text){
                            return;
                        }
                        let msgBody={
                            recvId : this.recvId,
                            content : this.text
                        }
                        let json = JSON.stringify(msgBody);
                        this.$refs.w.send(json);
                        isSend = true;
                        console.log(isSend)
                    }
                })
                // 离线发送
                if(!isSend){
                    if(this.recvId == "" || this.text == ""){
                        return
                    }
                    let msg = {
                        author:{
                            id: this.myinfo.id,
                            headimg: this.myinfo.headimg,
                            name: this.myinfo.name
                        },
                        content: this.text,
                        recvid: this.recvId,
                        state: 0,
                        time: this.getNowTime()
                    }
                    this.msgs.push(msg)
                }

                let message={
                    recvid : this.recvId,
                    content : this.text,
                    uid: this.myinfo.id,
                    time: null,
                    state: 0
                }
                axios.post("b-chat/message/saveChatMessage", message).then(res=>{
                    console.log("发送成功")
                })
                this.text = ""
            },
            relationshipById(){
                axios.get("b-user/relationship/getrelationshipById", {
                    params:{
                        id: this.myinfo.id
                    }
                }).then(res=>this.relationship = res.data.data)
            },

            psate(e){
                var clipboard = e.clipboardData;
                console.log(clipboard)
                if (clipboard.items[0].type.match(/image/)) {
                    let fd = new FormData();
                    let blob = clipboard.items[0].getAsFile();
                    let nm = "随机文件名.jpg"
                    fd.append("file",blob,nm);
                    fd.append("type", "image");
                    axios.post("upload/upload",fd).then(res=>{
                        if(res.data.code==1){
                            let webPath = res.data.data;
                            let text = "img:"+webPath;

                            let msgBody={
                                recvId : this.recvId,
                                content : text
                            }
                            let json = JSON.stringify(msgBody);

                            this.$refs.w.send(json)
                        }else{
                            this.$alter("文件上传失败!")
                        }
                    });
                }
            },
            chooserecv(id, uid){
                console.log("users", this.users)
                this.recvId = id;
                const name = document.getElementsByClassName("username")
                name[uid].style.color = "blue"
                axios.get("b-chat/message/getChatMessage", {
                    params:{

                        uid: this.myinfo.id,
                        recvId: this.recvId

                    }
                }).then(res=>{
                    // this.oldmsgs = res.data 是异步的，Vue 的数据更新和 DOM 渲染可能需要时间。会先执行下面的代码
                    this.oldmsgs = res.data;
                    // Vue 的 $nextTick 可以确保在 DOM 更新后执行滚动操作：
                    this.$nextTick(() => { // 确保 DOM 更新完成
                        this.$refs.chatMessages.scrollTo(0, this.$refs.chatMessages.scrollHeight);
                    });
                })

                axios.get("b-chat/message/updataMessageState", {
                    params:{
                        uid: this.recvId,
                        recvId: this.myinfo.id
                    }
                })



            },
            getNowTime(){
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
                const day = String(now.getDate()).padStart(2, '0');
                const hours = String(now.getHours()).padStart(2, '0');
                const minutes = String(now.getMinutes()).padStart(2, '0');
                const seconds = String(now.getSeconds()).padStart(2, '0');
                const formattedDate = `${year}-${month}-${day}`;
                const formattedTime = `${hours}:${minutes}:${seconds}`;
                const dateTime = `${formattedDate} ${formattedTime}`;
                return dateTime;
            }
        },
        mounted(){

        }

    })
</script>

</html>

<style>
    .send > * {
        float: right;

    }

    .recv > * {
        float: left;
    }

    .send, .recv {
        clear: both;
        padding: 5px 0px;
    }
    #msgs {
        flex: auto;
        box-sizing: border-box;
        padding: 10px;
    }

    .send-time{
        display: flex;
        justify-content: end;
        padding-bottom: 5px;
    }

    .recv-time{
        display: flex;
        justify-content: start;
        padding-bottom: 5px;
    }

    #msg {
        flex: none;
        width: 100%;
        height: 100px;
        box-sizing: border-box;
    }
    .user, .msg {
        padding: 5px;
    }
</style>